package com.ruoyi.system.controller;

import java.io.FileOutputStream;
import java.io.OutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.util.IOUtils;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.UtilException;
import com.ruoyi.system.domain.CusDeviceClock;
import com.ruoyi.system.domain.CusPersonClock;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.ICusDeviceClockService;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 设备打卡
 */
@Controller
@RequestMapping("/system/dclock")
public class CusDeviceClockController extends BaseController
{
    private String prefix = "system/deviceclock";

    @Autowired
    private ICusDeviceClockService cusDeviceClockService;
    
    @Autowired
    private SysUserMapper userMapper;
    
    @Autowired
    private ISysConfigService configService;
    
    // ----------------------------------------------------------------------------------------------------------------------
    
	@RequiresPermissions("system:clock:view")
    @GetMapping("/report")
    public String report()
    {    	
        return prefix + "/report";
    }
	
    @PostMapping("/report")
    @ResponseBody
    public TableDataInfo report(CusDeviceClock cusDeviceClock)
    {
        if(cusDeviceClock.getDeptName1() != null && !cusDeviceClock.getDeptName1().isEmpty()) { // 按照部门名称模糊查询时，取消按照部门ID查询
        	cusDeviceClock.setDept1(null);
        }else if(cusDeviceClock.getDept1() != null) { // 按照部门ID查询时，取消按照部门名称查询
        	cusDeviceClock.setDeptName1(null);
        }
        
        startPage();
        
        List<CusDeviceClock> list = cusDeviceClockService.selectCusPersonClockListByYM(cusDeviceClock);
        return getDataTable(list);
    }
    
    @PostMapping("/reportdetail")
    @ResponseBody
    public TableDataInfo reportdetail(CusDeviceClock cusDeviceClock)
    {
        startPage();
        
        // 选择设备参与多少项目
        List<CusDeviceClock> list = cusDeviceClockService.selectPersonProjectListByYM(cusDeviceClock);
        
        double allCount = 0;
        for(CusDeviceClock c : list){
        	c.setClockYear(cusDeviceClock.getClockYear());
        	c.setClockMonth(cusDeviceClock.getClockMonth());
        	
        	// 查找每个项目的打卡数据
        	List<CusDeviceClock> listdetail = cusDeviceClockService.selectCusPersonClockListDetailYM(c);
        	
        	// 统计每个项目的打卡时长
        	double count = 0;
        	for(CusDeviceClock detail : listdetail) {
        		if(detail.getStartDatetime() == null || detail.getEndDatetime() == null) {
            		continue;
            	}
            	
            	double startSec = detail.getStartDatetime().getTime()/(double)1000;
            	double endSec = detail.getEndDatetime().getTime()/(double)1000;
            	
            	double sec = endSec - startSec;
        		double min = sec / 60;
        		double hour = min / 60;
        		detail.setCountTime(String.format("%.2f", hour));
        		count += hour;
        		allCount += hour;
        	}
        	c.setCountTime(String.format("%.2f", count));
        }
        
        System.out.println(">>>>>>>>>" + allCount);
        CusDeviceClock heji = new CusDeviceClock();
        heji.setCountTime(String.format("%.2f", allCount));
        heji.setProject_name("");
        heji.setProject_status(-1);
        heji.setProject_code("合计");
        
        list.add(heji);
        
        return getDataTable(list);
    }
    
    // ----------------------------------------------------------------------------------------------------------------------
    
    /**
     * 导出人员研发列表
     */
    @RequestMapping("/exportrep")
    @ResponseBody
    public AjaxResult exportReport(HttpServletResponse rep, CusDeviceClock cusPersonClock){
        // 按照部门名称模糊查询，取消id查询
        if(cusPersonClock.getDeptName1() != null && !cusPersonClock.getDeptName1().isEmpty()) {
        	cusPersonClock.setDept1(null);
        }else if(cusPersonClock.getDept1() != null) {
        	cusPersonClock.setDeptName1(null);
        }
    	
    	List<CusDeviceClock> list = cusDeviceClockService.selectCusPersonClockListByYM(cusPersonClock);
    	
    	ArrayList<ArrayList<String>> partOne = new ArrayList<>();
    	LinkedHashMap<String, ArrayList<Double>> partTwo = new LinkedHashMap<>();
    	
    	ArrayList<Double> twoIteTotal = partTwo.get("参与研发的出勤时间（小时）");
    	if(twoIteTotal == null) {
    		partTwo.put("参与研发的出勤时间（小时）", twoIteTotal = new ArrayList<>());
    		for(int iii = 0; iii < list.size(); iii++) {
    			twoIteTotal.add((double) 0);
    		}
    	}
    	
    	for(int ii = 0; ii < list.size(); ii++) {
    		CusDeviceClock pc = list.get(ii);
    		
    		ArrayList<String> item = new ArrayList<>();
    		item.add(pc.getClockYear() + "-" + pc.getClockMonth());
    		item.add(pc.getDeptName1());
    		item.add(pc.getUser_name());
    		item.add(pc.getPosition_name());
    		item.add(pc.getDevice_name());
    		partOne.add(item);
    		
    		List<CusDeviceClock> list2 = cusDeviceClockService.selectPersonProjectListByYM(pc);

    		double allCount = 0;
            for(CusDeviceClock c : list2){
            	ArrayList<Double> twoIteMap = partTwo.get(c.getProject_code()+c.getProject_name());
            	if(twoIteMap == null) {
            		partTwo.put(c.getProject_code()+c.getProject_name(), twoIteMap = new ArrayList<>(list.size()));
            		for(int iii = 0; iii < list.size(); iii++) {
            			twoIteMap.add((double) 0);
            		}
            	}
            	
            	c.setClockYear(pc.getClockYear());
            	c.setClockMonth(pc.getClockMonth());
            	
            	//List<CusPersonClock> listdetail = cusPersonClockService.selectCusPersonClockList(c);
            	List<CusDeviceClock> listdetail = cusDeviceClockService.selectCusPersonClockListDetailYM(c);
            	
            	double count = 0;
            	for(CusDeviceClock detail : listdetail) {
            		if(detail.getStartDatetime() == null || detail.getEndDatetime() == null) {
                		continue;
                	}
                	
                	double startSec = detail.getStartDatetime().getTime()/(double)1000;
                	double endSec = detail.getEndDatetime().getTime()/(double)1000;
                	double restSec = 0;
                	
                	
                	double sec = endSec - startSec;
            		double min = sec / 60;
            		double hour = min / 60;
            		detail.setCountTime(String.format("%.2f", hour));
            		count += hour;
            		allCount += hour;
            	}
            	//twoIteMap.add(count);
            	twoIteMap.set(ii, count);
            	c.setCountTime(String.format("%.2f", count));
            }
            
        	//twoIteTotal.add(allCount);
        	twoIteTotal.set(ii, allCount);
    	}
    	
    	// heji
    	ArrayList<String> item = new ArrayList<>();
		item.add("合计");
		item.add("");
		item.add("");
		item.add("");
		item.add("");
		partOne.add(item);
		// heji
		for(String key : partTwo.keySet()) {
        	ArrayList<Double> arr = partTwo.get(key);
        	double targetValue = 0;
        	for(Double d : arr) {
        		targetValue += d;
        	}
        	arr.add(targetValue);
        }
		
		String mTip = "";
		if(cusPersonClock.getClockMonth() != null && cusPersonClock.getClockYear() != null) {
			mTip = cusPersonClock.getClockYear() + "年" + cusPersonClock.getClockMonth() + "月";
		}
    	
    	return writewb(rep, mTip, partOne, partTwo);
	}
    
    public AjaxResult exportExcel(HSSFWorkbook wb, String sheetName)
    {
        OutputStream out = null;
        try
        {
            String filename = ExcelUtil.encodingFilename(sheetName);
            out = new FileOutputStream(ExcelUtil.getAbsoluteFile(filename));
            wb.write(out);
            return AjaxResult.success(filename);
        }
        catch (Exception e)
        {
            throw new UtilException("导出Excel失败，请联系网站管理员！");
        }
        finally
        {
            IOUtils.closeQuietly(wb);
            IOUtils.closeQuietly(out);
        }
    }
    public AjaxResult exportExcel(SXSSFWorkbook wb, String sheetName)
    {
        OutputStream out = null;
        try
        {
            String filename = ExcelUtil.encodingFilename(sheetName);
            out = new FileOutputStream(ExcelUtil.getAbsoluteFile(filename));
            wb.write(out);
            return AjaxResult.success(filename);
        }
        catch (Exception e)
        {
            throw new UtilException("导出Excel失败，请联系网站管理员！");
        }
        finally
        {
            IOUtils.closeQuietly(wb);
            IOUtils.closeQuietly(out);
        }
    }
    
    public AjaxResult writewb(HttpServletResponse rep, String mTip, ArrayList<ArrayList<String>> partOne, HashMap<String, ArrayList<Double>> partTwo) {
    	//HSSFWorkbook wb = new HSSFWorkbook();
    	SXSSFWorkbook wb = new SXSSFWorkbook();
        Sheet sheet = wb.createSheet();

        //sheet.setColumnWidth(0, 1000);
        
        Font font = wb.createFont();
        font.setFontName("宋体");
        // 设置字体大小
        font.setFontHeightInPoints((short) 12);
        // 加粗
        font.setBold(true);
        
        CellStyle style = wb.createCellStyle();
        
        style.setBorderRight(BorderStyle.THIN);
        style.setBorderLeft(BorderStyle.THIN);
        style.setBorderTop(BorderStyle.THIN);
        style.setBorderBottom(BorderStyle.THIN);
        
        style.setFillPattern(style.getFillPatternEnum().SOLID_FOREGROUND);
        style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
        
        // 让单元格居中
        style.setAlignment(HorizontalAlignment.CENTER);
        // 左右居中
        style.setAlignment(HorizontalAlignment.CENTER);
        // 上下居中
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        //style.setWrapText(true);//设置自动换行
        style.setFont(font);
        
        // --------------------------------------------------
        
        CellStyle style2 = wb.createCellStyle();
        //style2.setWrapText(true);
        style2.setFillPattern(style.getFillPatternEnum().SOLID_FOREGROUND);
        style2.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
        style2.setAlignment(HorizontalAlignment.CENTER);
        style2.setAlignment(HorizontalAlignment.CENTER);
        style2.setVerticalAlignment(VerticalAlignment.CENTER);
        style2.setBorderRight(BorderStyle.THIN);
        style2.setBorderLeft(BorderStyle.THIN);
        style2.setBorderTop(BorderStyle.THIN);
        style2.setBorderBottom(BorderStyle.THIN);
        // --------------------------------------------
        
        
        
        Row row0 = sheet.createRow(0);
        CellRangeAddress region = new CellRangeAddress(0, 0, 0, (5 + partTwo.size()) -1);
        sheet.addMergedRegion(region);
        // -----------------------------------------
        Font font2 = wb.createFont();
        //font2.setFontName("仿宋_GB2312");
        font2.setBold(true);
        font2.setFontHeightInPoints((short) 20);
        //-----------------------------------------
        CellStyle setBorder = wb.createCellStyle();
        setBorder.setAlignment(HorizontalAlignment.CENTER); 
        setBorder.setFont(font2);
        //-----------------------------------------
        Cell first = row0.createCell(0);
        first.setCellType(CellType.STRING);
        first.setCellValue(mTip + "设备工时记录汇总表");
        first.setCellStyle(setBorder);
        //-----------------------------------------
        
        
        Row row1 = sheet.createRow(1);
        CellRangeAddress region1 = new CellRangeAddress(1, 1, 0, (3 + partTwo.size()) -1);
        sheet.addMergedRegion(region1);
        // -----------------------------------------
        Font font1 = wb.createFont();
        //font2.setFontName("仿宋_GB2312");
        font1.setBold(false);
        font1.setFontHeightInPoints((short) 14);
        //-----------------------------------------
        CellStyle setBorder1 = wb.createCellStyle();
        setBorder1.setAlignment(HorizontalAlignment.LEFT); 
        setBorder1.setFont(font1);
        //-----------------------------------------
        Cell first1 = row1.createCell(0);
        first1.setCellType(CellType.STRING);
        first1.setCellValue("单位：中烟摩迪（江门）纸业有限公司");
        first1.setCellStyle(setBorder1);
        //-----------------------------------------
        
        
        
        int startno = 2;
        int rowIndex = 0 + startno;
        Row row = sheet.createRow(rowIndex);
        row.setHeight((short) 1600);
        
        
        int index = 0;
        // 月份
        Cell indexCell = row.createCell(index);
        indexCell.setCellType(CellType.STRING);
        indexCell.setCellStyle(style);//设置表头样式
        indexCell.setCellValue("月份");
        sheet.setColumnWidth(index++, (int)((15 + 0.72) * 256));
        //sheet.autoSizeColumn((short) index++);
        // 部门
        indexCell = row.createCell(index);
        indexCell.setCellType(CellType.STRING);
        indexCell.setCellStyle(style);//设置表头样式
        indexCell.setCellValue("部门1");
        sheet.setColumnWidth(index++, (int)((30 + 0.72) * 256));
        //sheet.autoSizeColumn((short) index++);
        // 名字
        indexCell = row.createCell(index);
        indexCell.setCellType(CellType.STRING);
        indexCell.setCellStyle(style);//设置表头样式
        indexCell.setCellValue("名字");
        sheet.setColumnWidth(index++, (int)((12 + 0.72) * 256));
        //sheet.autoSizeColumn((short) index++);
        // 位置
        indexCell = row.createCell(index);
        indexCell.setCellType(CellType.STRING);
        indexCell.setCellStyle(style);//设置表头样式
        indexCell.setCellValue("位置");
        sheet.setColumnWidth(index++, (int)((15 + 0.72) * 256));
        // 设备
        indexCell = row.createCell(index);
        indexCell.setCellType(CellType.STRING);
        indexCell.setCellStyle(style);//设置表头样式
        indexCell.setCellValue("设备");
        sheet.setColumnWidth(index++, (int)((25 + 0.72) * 256));
        
        for(String key : partTwo.keySet()) {
        	indexCell = row.createCell(index);
            indexCell.setCellType(CellType.STRING);
            indexCell.setCellStyle(style);//设置表头样式
            indexCell.setCellValue("    "+key+"    ");
            sheet.setColumnWidth(index++, (int)((40 + 0.72) * 256));
            //sheet.autoSizeColumn((short) index++);
        }
        
        // -------------------------------------------
        
        for(int i = 0; i < partOne.size(); i++) {
        	rowIndex++;
        	index=0;
        	
        	ArrayList<String> partOneItem = partOne.get(i);
        	
        	Row drow = sheet.createRow(rowIndex);
        	drow.setHeight((short) 800);
        	
        	// 月份
            indexCell = drow.createCell(index);
            indexCell.setCellType(CellType.STRING);
            indexCell.setCellStyle(style2);
            indexCell.setCellValue(partOneItem.get(index++));
            // 部门
            indexCell = drow.createCell(index);
            indexCell.setCellType(CellType.STRING);
            indexCell.setCellStyle(style2);
            indexCell.setCellValue(partOneItem.get(index++));
            // 名字
            indexCell = drow.createCell(index);
            indexCell.setCellType(CellType.STRING);
            indexCell.setCellStyle(style2);
            indexCell.setCellValue(partOneItem.get(index++));
            // 位置
            indexCell = drow.createCell(index);
            indexCell.setCellType(CellType.STRING);
            indexCell.setCellStyle(style2);
            indexCell.setCellValue(partOneItem.get(index++));
            // 设备
            indexCell = drow.createCell(index);
            indexCell.setCellType(CellType.STRING);
            indexCell.setCellStyle(style2);
            indexCell.setCellValue(partOneItem.get(index++));
            
            for(String key : partTwo.keySet()) {
            	ArrayList<Double> arr = partTwo.get(key);
            	double targetValue = 0;
            	if((rowIndex - 1 - startno) < arr.size()) {
            		targetValue = arr.get(rowIndex - 1 - startno);
            	}
            	
            	indexCell = drow.createCell(index);
                indexCell.setCellType(CellType.STRING);
                indexCell.setCellStyle(style2);
                indexCell.setCellValue(String.format("%.2f", targetValue));
                index++;
                //sheet.autoSizeColumn((short) index++);
            }
        }
        
        
        Row rowLast = sheet.createRow(rowIndex+2);
//      CellRangeAddress region1 = new CellRangeAddress(1, 1, 0, (3 + partTwo.size()) -1);
//      sheet.addMergedRegion(region1);
      
      // -----------------------------------------
      Font font3 = wb.createFont();
      //font2.setFontName("仿宋_GB2312");
      font1.setBold(false);
      font1.setFontHeightInPoints((short) 12);
      //-----------------------------------------
      CellStyle setBorder3 = wb.createCellStyle();
      setBorder1.setAlignment(HorizontalAlignment.LEFT); 
      setBorder1.setFont(font3);
      //-----------------------------------------
      Cell zbr = rowLast.createCell(0);
      zbr.setCellType(CellType.STRING);
      zbr.setCellValue("制表人：");
      zbr.setCellStyle(setBorder3);
      
      Cell xm = rowLast.createCell(3);
      xm.setCellType(CellType.STRING);
      xm.setCellValue("研发项目负责人：");
      xm.setCellStyle(setBorder3);
      
      Cell zg = rowLast.createCell(6);
      zg.setCellType(CellType.STRING);
      zg.setCellValue("主管副总：");
      zg.setCellStyle(setBorder3);
      //-----------------------------------------
      
        // --------------------------------------------------------------------------
        
//        rep.setContentType("application/vnd.ms-excel");
//        rep.setHeader("Content-disposition", "attachment;filename=\"" + "report.xls" + "\"");
//        OutputStream ouputStream = null;
//        try {
//            ouputStream = rep.getOutputStream();
//            wb.write(ouputStream);
//            wb.close();
//        } catch (IOException e) {
//			e.printStackTrace();
//		} finally {
//            try {
//				ouputStream.close();
//			} catch (Exception e) {
//				e.printStackTrace();
//			}
//        }
        
        return exportExcel(wb, "汇总报表");
    }
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    @RequiresPermissions("system:clock:view")
    @GetMapping()
    public String clock()
    {
        return prefix + "/clock";
    }

    /**
     * 查询设备打卡列表
     */
    @RequiresPermissions("system:clock:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(CusDeviceClock cusDeviceClock)
    {
    	if(cusDeviceClock.getClockDay() == null) {
    		cusDeviceClock.setClockDay(1L);
    	}
    	if(cusDeviceClock.getClockDayend() == null) {
    		cusDeviceClock.setClockDayend(1L);
    	}
    	
    	cusDeviceClock.setClockDayStr(cusDeviceClock.getClockDay() < 10 ? "0" + cusDeviceClock.getClockDay() : cusDeviceClock.getClockDay() + "");
    	cusDeviceClock.setClockDayendStr(cusDeviceClock.getClockDayend() < 10 ? "0" + cusDeviceClock.getClockDayend() : cusDeviceClock.getClockDayend() + "");
    	
    	if(cusDeviceClock.getClockMonth() != null) {
    		cusDeviceClock.setClockMonthStr(cusDeviceClock.getClockMonth() < 10 ? "0" + cusDeviceClock.getClockMonth() : cusDeviceClock.getClockMonth() + "");
    		//cusPersonClock.setClockMonthendStr(cusPersonClock.getClockMonthend() < 10 ? "0" + cusPersonClock.getClockMonthend() : cusPersonClock.getClockMonthend() + "");
    	}
    	if(cusDeviceClock.getClockMonthend() != null) {
    		//cusPersonClock.setClockMonthStr(cusPersonClock.getClockMonth() < 10 ? "0" + cusPersonClock.getClockMonth() : cusPersonClock.getClockMonth() + "");
    		cusDeviceClock.setClockMonthendStr(cusDeviceClock.getClockMonthend() < 10 ? "0" + cusDeviceClock.getClockMonthend() : cusDeviceClock.getClockMonthend() + "");
    	}
    	
        // 按照部门名称模糊查询，取消id查询
        if(cusDeviceClock.getDeptName1() != null && !cusDeviceClock.getDeptName1().isEmpty()) {
//        	SysDept d = deptService.selectDeptById(cusPersonClock.getDept1());
//        	cusPersonClock.setDeptName1(d.getDeptName());
        	cusDeviceClock.setDept1(null);
        }else if(cusDeviceClock.getDept1() != null) {
        	cusDeviceClock.setDeptName1(null);
        }
        
        startPage();
        List<CusDeviceClock> list = cusDeviceClockService.selectCusDeviceClockList(cusDeviceClock);
        return getDataTable(list);
    }
    

    /**
     * 导出设备打卡列表
     */
    @RequiresPermissions("system:clock:export")
    @Log(title = "设备打卡", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(CusDeviceClock cusDeviceClock)
    {
    	if(cusDeviceClock.getClockDay() == null) {
    		cusDeviceClock.setClockDay(1L);
    	}
    	if(cusDeviceClock.getClockDayend() == null) {
    		cusDeviceClock.setClockDayend(1L);
    	}
    	
    	cusDeviceClock.setClockDayStr(cusDeviceClock.getClockDay() < 10 ? "0" + cusDeviceClock.getClockDay() : cusDeviceClock.getClockDay() + "");
    	cusDeviceClock.setClockDayendStr(cusDeviceClock.getClockDayend() < 10 ? "0" + cusDeviceClock.getClockDayend() : cusDeviceClock.getClockDayend() + "");
    	
    	if(cusDeviceClock.getClockMonth() != null) {
    		cusDeviceClock.setClockMonthStr(cusDeviceClock.getClockMonth() < 10 ? "0" + cusDeviceClock.getClockMonth() : cusDeviceClock.getClockMonth() + "");
    		//cusPersonClock.setClockMonthendStr(cusPersonClock.getClockMonthend() < 10 ? "0" + cusPersonClock.getClockMonthend() : cusPersonClock.getClockMonthend() + "");
    	}
    	if(cusDeviceClock.getClockMonthend() != null) {
    		//cusPersonClock.setClockMonthStr(cusPersonClock.getClockMonth() < 10 ? "0" + cusPersonClock.getClockMonth() : cusPersonClock.getClockMonth() + "");
    		cusDeviceClock.setClockMonthendStr(cusDeviceClock.getClockMonthend() < 10 ? "0" + cusDeviceClock.getClockMonthend() : cusDeviceClock.getClockMonthend() + "");
    	}
    	
        List<CusDeviceClock> list = cusDeviceClockService.selectCusDeviceClockList(cusDeviceClock);
        for(CusDeviceClock c : list){
        	if(c.getStartDatetime() == null || c.getEndDatetime() == null) {
            	Calendar calendar = Calendar.getInstance();
            	calendar.set(Calendar.YEAR, c.getClockYear().intValue());
            	calendar.set(Calendar.MONTH, c.getClockMonth().intValue() - 1);
            	calendar.set(Calendar.DAY_OF_MONTH, c.getClockDay().intValue());
            	
            	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            	String ddate = sdf.format(calendar.getTime());
          
            	c.setDdate(ddate);
            	c.setWeek(getWeek(calendar.getTime()));
            	
        		continue;
        	}
        	
        	double startSec = c.getStartDatetime().getTime()/(double)1000;
        	double endSec = c.getEndDatetime().getTime()/(double)1000;
        	
        	double sec = endSec - startSec;
    		double min = sec / 60;
    		double hour = min / 60;
    		
    		c.setCountTime(String.format("%.2f", hour));
    		
        	Calendar calendar = Calendar.getInstance();
        	calendar.set(Calendar.YEAR, c.getClockYear().intValue());
        	calendar.set(Calendar.MONTH, c.getClockMonth().intValue() - 1);
        	calendar.set(Calendar.DAY_OF_MONTH, c.getClockDay().intValue());
        	
        	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        	String ddate = sdf.format(calendar.getTime());
      
        	c.setDdate(ddate);
        	c.setWeek(getWeek(calendar.getTime()));
        }
        	
		String mTip = "";
		if(cusDeviceClock.getClockMonth() != null && cusDeviceClock.getClockYear() != null) {
			mTip = cusDeviceClock.getClockYear() + "年" + cusDeviceClock.getClockMonth() + "月";
		}
		
        ExcelUtil<CusDeviceClock> util = new ExcelUtil<CusDeviceClock>(CusDeviceClock.class);
        return util.exportExcel2(list, mTip + "设备工时记录明细表");
    }

    public static String getWeek(Date date){
    	// String[] weeks = {"星期日","星期一","星期二","星期三","星期四","星期五","星期六"};
    	String[] weeks = {"7","1","2","3","4","5","6"};
    	Calendar cal = Calendar.getInstance();
    	cal.setTime(date);
    	int week_index = cal.get(Calendar.DAY_OF_WEEK) - 1;
    	if(week_index<0){
    	week_index = 0;
    	}
    	return weeks[week_index];
    	}
    /**
     * 新增设备打卡
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }
    
    /**
     * 新增设备打卡
     */
    @GetMapping("/adds")
    public String adds(String ids, String names, ModelMap mmap)
    {
    	mmap.put("ids", ids);
    	mmap.put("names", names);
        return prefix + "/adds";
    }

    /**
     * 新增保存设备打卡
     */
    @RequiresPermissions("system:clock:add")
    @Log(title = "设备打卡", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(String deviceIds, CusDeviceClock cusDeviceClock)
    {
    	
    	String timeLimit = configService.selectConfigByKey("sys.daka.timelimit");
    	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date tEnd = null;
    	try {
			tEnd = sdf.parse(timeLimit);
		} catch (ParseException e) {
			e.printStackTrace();
		}
    	
    	cusDeviceClock.setEndPersionId(cusDeviceClock.getStartPersionId());
    	
    	// 获取当前的用户信息
    	SysUser currentUser = ShiroUtils.getSysUser();
//    	if (cusDeviceClock.getEndPersionId() == null) {
//    		cusDeviceClock.setDept1(currentUser.getDeptId());
//        	cusDeviceClock.setDept2(currentUser.getDeptId2());
//    		cusDeviceClock.setEndPersionId(currentUser.getUserId());
//		}
    	if (cusDeviceClock.getStartPersionId() == null) {
    		cusDeviceClock.setDept1(currentUser.getDeptId());
        	cusDeviceClock.setDept2(currentUser.getDeptId2());
    		cusDeviceClock.setStartPersionId(currentUser.getUserId());
		}else {
			SysUser u = userMapper.selectUserById(cusDeviceClock.getStartPersionId());
			cusDeviceClock.setDept1(u.getDeptId());
        	cusDeviceClock.setDept2(u.getDeptId2());
		}
    	
    	String tipString = "";
    	String[] ids = deviceIds.split(",");
    	int effectRows = 0;
    	for(String id : ids) {
    		cusDeviceClock.setDeviceId(Long.valueOf(id));
    		
    		if(cusDeviceClock.getStartDatetime() != null && cusDeviceClock.getStartDatetime().getTime() < tEnd.getTime()) {
    			tipString = "该时间段禁止打卡";
        		continue;
        	}
        	if(cusDeviceClock.getEndDatetime() != null && cusDeviceClock.getEndDatetime().getTime() < tEnd.getTime()) {
        		tipString = "该时间段禁止打卡";
        		continue;
        	}
        	
    		effectRows += cusDeviceClockService.insertCusDeviceClock(cusDeviceClock);
    	}
    	return toAjax(effectRows, tipString);
        
    	// return toAjax(cusDeviceClockService.insertCusDeviceClock(cusDeviceClock));
    }
    
    /**
     * 批量人员研发打卡
     */
    @Log(title = "手机批量设备打卡", businessType = BusinessType.INSERT)
    @RequestMapping("/dlclock")
    @ResponseBody
    public AjaxResult plclock(String ids, boolean issb, long operate, Date clockdates, CusDeviceClock cusDeviceClock, ModelMap mmap)
    {
    	String[] idarr = ids.split(",");
    	for(String id : idarr) {
    		long did = Long.valueOf(id);
    		cusDeviceClock.setDeviceId(did);
    		deviceClock(issb, clockdates, operate, cusDeviceClock);
    	}
    	return toAjax(1);
    }
    
    public int deviceClock(boolean issb, Date clockdates, long operate, CusDeviceClock cusDeviceClock)
    {
    	String timeLimit = configService.selectConfigByKey("sys.daka.timelimit");
    	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date tEnd = null;
    	try {
			tEnd = sdf.parse(timeLimit);
		} catch (ParseException e) {
			e.printStackTrace();
		}
    	
    	cusDeviceClock.setDept1(null);
		cusDeviceClock.setDept2(null);
		cusDeviceClock.setStartPersionId(null);
		cusDeviceClock.setStartDatetime(null);
		cusDeviceClock.setEndPersionId(null);
		cusDeviceClock.setEndDatetime(null);
		
    	List<CusDeviceClock> list = cusDeviceClockService.selectCusDeviceClockList2(cusDeviceClock);
    	 
    	if(list.size() == 0) {
    		SysUser user = userMapper.selectUserById(operate);
    		cusDeviceClock.setDept1(user.getDeptId());
    		cusDeviceClock.setDept2(user.getDeptId2());
    		
        	if(issb) {
        		cusDeviceClock.setStartPersionId(operate);
        		cusDeviceClock.setStartDatetime(new Date());
        		if(clockdates != null) {
        			cusDeviceClock.setStartDatetime(clockdates);
        		}
        	}else {
        		cusDeviceClock.setEndPersionId(operate);
        		cusDeviceClock.setEndDatetime(new Date());
        		if(clockdates != null) {
        			cusDeviceClock.setEndDatetime(clockdates);
        		}
        	}
        	
        	if(cusDeviceClock.getStartDatetime() != null && cusDeviceClock.getStartDatetime().getTime() < tEnd.getTime()) {
        		return 0;
        	}
        	if(cusDeviceClock.getEndDatetime() != null && cusDeviceClock.getEndDatetime().getTime() < tEnd.getTime()) {
        		return 0;
        	}
        	
    		return cusDeviceClockService.insertCusDeviceClock(cusDeviceClock);
    	}else {
    		CusDeviceClock c = list.get(list.size() - 1);
    		
    		// 已存在记录：如果是下班卡 并且 该记录没有打下班，更新
        	if(c.getEndDatetime() == null && !issb) {
        		c.setEndPersionId(operate);
        		c.setEndDatetime(new Date());
        		if(clockdates != null) {
        			c.setEndDatetime(clockdates);
        		}
        		
        		return cusDeviceClockService.updateCusDeviceClock(c);
        	}else {
        		SysUser user = userMapper.selectUserById(operate);
        		cusDeviceClock.setDept1(user.getDeptId());
        		cusDeviceClock.setDept2(user.getDeptId2());
        		
            	if(issb) {
            		cusDeviceClock.setStartPersionId(operate);
            		cusDeviceClock.setStartDatetime(new Date());
            		if(clockdates != null) {
            			cusDeviceClock.setStartDatetime(clockdates);
            		}
            	}else {
            		cusDeviceClock.setEndPersionId(operate);
            		cusDeviceClock.setEndDatetime(new Date());
            		if(clockdates != null) {
            			cusDeviceClock.setEndDatetime(clockdates);
            		}
            	}
            	
        		return cusDeviceClockService.insertCusDeviceClock(cusDeviceClock);
        	}
    		
//    		
//        	if(issb) {
//        		c.setStartPersionId(operate);
//        		c.setStartDatetime(new Date());
//        		if(clockdates != null) {
//        			cusDeviceClock.setStartDatetime(clockdates);
//        		}
//        	}else {
//        		c.setEndPersionId(operate);
//        		c.setEndDatetime(new Date());
//        		if(clockdates != null) {
//        			cusDeviceClock.setEndDatetime(clockdates);
//        		}
//        	}
//        	return cusDeviceClockService.updateCusDeviceClock(c);
    	}
    }

    /**
     * 修改设备打卡
     */
    @GetMapping("/edit/{ID}")
    public String edit(@PathVariable("ID") Long ID, ModelMap mmap)
    {
        CusDeviceClock cusDeviceClock = cusDeviceClockService.selectCusDeviceClockByID(ID);
        mmap.put("cusDeviceClock", cusDeviceClock);
        return prefix + "/edit";
    }

    /**
     * 修改保存设备打卡
     */
    @RequiresPermissions("system:clock:edit")
    @Log(title = "设备打卡", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(CusDeviceClock cusDeviceClock)
    {
    	String timeLimit = configService.selectConfigByKey("sys.daka.timelimit");
    	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date tEnd = null;
    	try {
			tEnd = sdf.parse(timeLimit);
		} catch (ParseException e) {
			e.printStackTrace();
		}
    	
    	if(cusDeviceClock.getStartDatetime() != null && cusDeviceClock.getStartDatetime().getTime() < tEnd.getTime()) {
    		return toAjax(0, "禁止修改该时间段的打卡");
    	}
    	if(cusDeviceClock.getEndDatetime() != null && cusDeviceClock.getEndDatetime().getTime() < tEnd.getTime()) {
    		return toAjax(0, "禁止修改该时间段的打卡");
    	}
    	
        return toAjax(cusDeviceClockService.updateCusDeviceClock(cusDeviceClock));
    }

    /**
     * 删除设备打卡
     */
    @RequiresPermissions("system:clock:remove")
    @Log(title = "设备打卡", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
    	String timeLimit = configService.selectConfigByKey("sys.daka.timelimit");
    	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date tEnd = null;
    	try {
			tEnd = sdf.parse(timeLimit);
		} catch (ParseException e) {
			e.printStackTrace();
		}
    	
    	
    	
    	int delCount = 0;
    	String[] idset = ids.split(",");
    	String tip = "";
    	for(String id : idset) {
    		CusDeviceClock clock = cusDeviceClockService.selectCusDeviceClockByID(Long.parseLong(id));
    		
    		if(clock.getStartDatetime() != null && clock.getStartDatetime().getTime() < tEnd.getTime()) {
    			tip = "部分打卡记录由于时间锁定被禁止删除";
        		continue;
        	}
        	if(clock.getEndDatetime() != null && clock.getEndDatetime().getTime() < tEnd.getTime()) {
        		tip = "部分打卡记录由于时间锁定被禁止删除";
        		continue;
        	}
    		
    		cusDeviceClockService.deleteCusDeviceClockByID(clock.getID());
    		delCount++;
    	}
    	
        return toAjax(delCount, tip);
        
        //return toAjax(cusDeviceClockService.deleteCusDeviceClockByIDs(ids));
    }
}
